package game;

import java.util.LinkedList;

/**
 * @author Psycho
 * @create 2021-07-18-16:18
 */
public class Snake {
    private boolean isAlive = true;
    private LinkedList<Node> body;//蛇的身体
    private Direction direction = Direction.LEFT;       //给个方向启动

    //构造方法，创建对象初始化蛇
    public Snake(){
        initSnake();
    }

    //初始化蛇身
    private void initSnake() {
        //创建集合
        body = new LinkedList<>();
        //初始化6个节点
        body.add(new Node(16,20));
        body.add(new Node(17,20));
        body.add(new Node(18,20));
        body.add(new Node(19,20));
        body.add(new Node(20,20));
        body.add(new Node(21,20));
        body.add(new Node(22,20));
        body.add(new Node(23,20));
        body.add(new Node(24,20));
        body.add(new Node(25,20));
    }

    public void move(){
        if(isAlive){
            //获得蛇头
            Node head = body.getFirst();
            switch (direction){
                case UP:
                    body.addFirst(new Node(head.getX(), head.getY()-1));
                    break;
                case DOWN:
                    body.addFirst(new Node(head.getX(), head.getY()+1));
                    break;
                case LEFT:
                    body.addFirst(new Node(head.getX()-1, head.getY()));
                    break;
                case RIGHT:
                    body.addFirst(new Node(head.getX()+1, head.getY()));
                    break;
            }
            body.removeLast();
            head = body.getFirst();
            if(head.getX()<0||head.getY()<0||head.getY()>39||head.getX()>39){
                isAlive = false;
            }
            for (int i = 1; i <body.size() ; i++) {
                Node node = body.get(i);
                if(node.getX()== head.getX()&&node.getY()==head.getY()){
                    isAlive = false;
                }
            }
        }
    }

    public LinkedList<Node> getBody() {
        return body;
    }

    public void setBody(LinkedList<Node> body) {
        this.body = body;
    }

    public Direction getDirection() {
        return direction;
    }

    public void setDirection(Direction direction) {
        this.direction = direction;
    }

    public void eat(Node food) {
        //获得蛇头
        Node head = body.getFirst();
        switch (direction){
            case UP:
                body.addFirst(new Node(head.getX(), head.getY()-1));
                break;
            case DOWN:
                body.addFirst(new Node(head.getX(), head.getY()+1));
                break;
            case LEFT:
                body.addFirst(new Node(head.getX()-1, head.getY()));
                break;
            case RIGHT:
                body.addFirst(new Node(head.getX()+1, head.getY()));
                break;
        }
    }
}
